package io.gitee.welson.sensitive.config;

import io.gitee.welson.sensitive.condition.ConditionEvaluator;
import io.gitee.welson.sensitive.converter.StringSensitiveConverter;
import io.gitee.welson.sensitive.service.DefaultSensitiveExportService;
import io.gitee.welson.sensitive.service.SensitiveExportService;
import io.gitee.welson.sensitive.strategy.SensitiveStrategyFactory;
import io.gitee.welson.sensitive.writer.DefaultExportWriter;
import io.gitee.welson.sensitive.writer.ExportWriter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.expression.BeanFactoryResolver;

/**
 * 敏感数据导出自动配置类
 *
 * @author welson
 */
@Configuration
@EnableConfigurationProperties(SensitiveExportProperties.class)
@ConditionalOnProperty(prefix = "sensitive.export", name = "enabled", havingValue = "true", matchIfMissing = true)
@Import(SensitiveStrategyRegistrar.class)
public class SensitiveExportAutoConfiguration {

    /**
     * 配置脱敏策略工厂
     */
    @Bean
    @ConditionalOnMissingBean
    public SensitiveStrategyFactory sensitiveStrategyFactory() {
        return new SensitiveStrategyFactory();
    }

    @Bean
    @ConditionalOnMissingBean
    public ConditionEvaluator conditionEvaluator(BeanFactoryResolver beanFactoryResolver) {
        return new ConditionEvaluator(beanFactoryResolver);
    }

    @Bean
    @ConditionalOnMissingBean
    public StringSensitiveConverter stringSensitiveConverter(
            SensitiveStrategyFactory strategyFactory,
            SensitiveExportProperties properties,
            ConditionEvaluator conditionEvaluator) {
        return new StringSensitiveConverter(strategyFactory, properties, conditionEvaluator);
    }

    @Bean
    @ConditionalOnMissingBean
    public ExportWriter exportWriter(SensitiveExportProperties properties,
                                     StringSensitiveConverter stringSensitiveConverter) {
        return new DefaultExportWriter(properties, stringSensitiveConverter);
    }

    @Bean
    @ConditionalOnMissingBean
    public SensitiveExportService sensitiveExportService(ExportWriter exportWriter,
                                                         SensitiveExportProperties properties) {
        return new DefaultSensitiveExportService(exportWriter, properties);
    }

    @Bean
    @ConditionalOnMissingBean
    public BeanFactoryResolver beanFactoryResolver(ConfigurableApplicationContext applicationContext) {
        return new BeanFactoryResolver(applicationContext);
    }
} 